from drf_yasg.utils import swagger_auto_schema
from rest_framework.decorators import action
from rest_framework.views import APIView
from rest_framework.views import Request
from common.response import result
from zhipuai import ZhipuAI
import requests
import json

class Demo(APIView):

    client = ZhipuAI(api_key="1623ba7fdb8373a4db64addcdb52d9e9.ilwdshbLnW5FhsYgc")

    @action(methods=['POST'], detail=False)
    def post(self, request: Request):
        rtn = self.__getAnswer(request.data['info'])
        return result.success(data=rtn)

    def __getAnswer(self, info: str):
        response = self.client.chat.completions.create(
            model="glm-4",  # 填写需要调用的模型名称
            messages=[
                {"role": "system", "content": "熟悉各种xml标准的语法，精准为用户提供帮助"},
                {"role": "user", "content": f"内容如下:\n{info}\n转换要求:将以上内容转换为dita标准的xml；中文显示；只输出xml内容。"},
            ],
        )
        result = str(response.choices[0].message.content)
        bgn = result.find("```") + 6
        end = result.rfind("```")
        return result[bgn:end]

    def toOllama(self, info: str, host='localhost', port=11434):
        url = f"http://{host}:{port}/api/chat"
        message = f"内容如下:\n{info}\n转换要求:将以上内容转换为dita标准的xml；中文显示；只输出xml内容。"
        payload = {
            "model": "qwen:14b",
            "messages": [
                {"role": "system", "content": "熟悉各种xml标准的语法，精准为用户提供帮助"},
                {"role": "user", "content": message}
            ]
        }
        response = requests.post(url, json=payload)
        if response.status_code == 200:
            response_content = ""
            for line in response.iter_lines():
                if line:
                    response_content += json.loads(line)["message"]["content"]
            return response_content
        else:
            return f"Error: {response.status_code} - {response.text}"
